package sxe.core.cs511.team2_2;

import javax.imageio.ImageIO;
import javax.swing.*;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.data.time.Millisecond;
import org.jfree.data.time.RegularTimePeriod;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;


/** OVERVIEW:  This class provides a graphical user interface to test the methods in the blob detector and tracker classes.
 *  This class was developed in order to display our work on our website and does not use any of the snBench architecure.
 * @author lisap
 *
 */

public class PersonDetectorApplet extends Applet{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	BlobDetectorControls controls = null;
	BlobDetector blobDetector = null;
	BlobBag b = null;
	String hostname="cs-people.bu.edu";
	String sequence_name="TESTIMG";
	Tracker tracker = new Tracker(-1,0);
	int count = 0;
	int index = 1;
	TimeSeriesCollection tsdata = new TimeSeriesCollection();
	TimeSeries series = new TimeSeries("a series", Millisecond.class);
	
	
	public class ImagePanel extends JPanel{
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		public BufferedImage myImage;
		
		public ImagePanel(BufferedImage bi){
			myImage = bi;
			this.setPreferredSize(new Dimension(300, 300)); 
		}
		
		public ImagePanel(){
			this.setPreferredSize(new Dimension(300,300)); 
		}
		
		public void paintComponent(Graphics g){
			super.paintComponent(g);
			Graphics2D g2 = (Graphics2D)g;
			g2.drawImage(myImage, null, 0, 0);
		}
		
	}
	
	public class BlobDetectorControls extends JPanel implements ActionListener{
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		public ImagePanel imagepanel = null;
		public ImagePanel imagepanel2 = null;
		public ImagePanel imagepanel3 = null;
		private JButton blobButton = null;
		private JButton playButton = null;
		private JButton graphButton = null;
		private JPanel centerpanel = null;
		public JLabel frameLabel = null;
		public JLabel countLabel = null;
		
		public BlobDetectorControls(BufferedImage bi){
			if (bi != null)
				imagepanel = new ImagePanel(bi);
			else
				imagepanel = new ImagePanel();
			centerpanel = new JPanel();
			imagepanel2 = new ImagePanel();
			imagepanel3 = new ImagePanel();
			JPanel buttonpanel = new JPanel();
			playButton = new JButton("play");
			blobButton = new JButton("show blobs");
			graphButton = new JButton("show graph");
			frameLabel = new JLabel("frame: 0");
			countLabel = new JLabel("grad lounge count: 0");
			
			buttonpanel.setLayout(new GridLayout(2,3));
			buttonpanel.add(playButton);
			buttonpanel.add(blobButton);
			//buttonpanel.add(graphButton);
			buttonpanel.add(frameLabel);
			buttonpanel.add(countLabel);

			this.setLayout(new BorderLayout());
			centerpanel.add(imagepanel);
			//centerpanel.add(imagepanel2);
			centerpanel.add(imagepanel3);
			this.add(centerpanel, BorderLayout.CENTER);
			this.add(buttonpanel, BorderLayout.SOUTH);
			//this.add(new JLabel("backgound image", SwingConstants.CENTER), BorderLayout.NORTH);
			

			playButton.addActionListener(this);
			blobButton.addActionListener(this);
			graphButton.addActionListener(this);
			this.repaint();
		}

		public void actionPerformed(ActionEvent ev) {
			// when the play button is pushed, display next image

			if (ev.getSource() == this.playButton){
				URL url = null;
				try{
			  
				url = new URL("http://"+hostname+"/lisap/CS511/TestImages/"+sequence_name+"_" + index + ".png");
				index++;
				BufferedImage bi1 = null;
				bi1 = ImageIO.read(url);
				controls.frameLabel.setText("frame: " + index);
				
				imagepanel2.myImage = blobDetector.getBackground();
				imagepanel.myImage = bi1;
				imagepanel.repaint();
				imagepanel2.repaint();

				count++;
				
				b = blobDetector.detectBlobs(bi1); //called with object of interest  
				
				tracker.add(b);
				int count = tracker.computeCount(1000);
				System.out.println("blogbagsize= "+ b.size());
				System.out.println("Tracks="+tracker.size());
				controls.countLabel.setText("grad lounge count: " + count);
				
				System.out.println("Count="+count);
				
				// update chart in case someone wants to display it
		
				Date adate = Calendar.getInstance().getTime();
				RegularTimePeriod time = RegularTimePeriod.createInstance(Millisecond.class, adate, RegularTimePeriod.DEFAULT_TIME_ZONE);
				series.add(time, (double)count);
				tsdata.addSeries(series);
				
				String title = "Grad Lounge Activity";
				String xAxisLabel = "time";
				String yAxisLabel = "Number of people in lounge";
				
				
				 JFreeChart chart = ChartFactory.createTimeSeriesChart(title, // title
							xAxisLabel, // X-axis label
							yAxisLabel, // Y-axis label
							tsdata, // Get Data.
							false, // Create legend?
							false, // Generate tooltips?
							false // Generate URLs?
							);

				imagepanel3.myImage = chart.createBufferedImage(300, 300);
				imagepanel3.repaint();
				
				
				}catch(Exception e){
					System.out.println("Unable to open file " + e.getMessage() + " " + url.toString());
					e.printStackTrace();
				}

			}
			if (ev.getSource() == this.blobButton){
				// draw boxes to show the blob locations
				if (b != null){
					BufferedImage imout = blobDetector.drawBoundingBoxes(b);
					imagepanel.myImage = imout;
					imagepanel.repaint();
				}
			}
			if (ev.getSource() == this.graphButton){
				// show graph, up through current frame
				String title = "Grad Lounge Activity";
				String xAxisLabel = "time";
				String yAxisLabel = "Number of people in lounge";
				
				
				 JFreeChart chart = ChartFactory.createTimeSeriesChart(title, // title
							xAxisLabel, // X-axis label
							yAxisLabel, // Y-axis label
							tsdata, // Get Data.
							false, // Create legend?
							false, // Generate tooltips?
							false // Generate URLs?
							);

				imagepanel3.myImage = chart.createBufferedImage(300, 300);
				imagepanel3.repaint();
			}
		}

	}
	
	public PersonDetectorApplet(){
	  

	}

    /** This method sets up the graphical user interface elements */
	public void init() {
		try{
			blobDetector = new BlobDetector(1, true);

		        java.net.InetAddress addr = java.net.InetAddress.getLocalHost();
		    
		        // Get hostname
		        String realhostname = addr.getHostName();
			//if(realhostname.equalsIgnoreCase("ALIRT-BS")) hostname="localhost"; // if tunneling
			URL url = new URL("http://"+hostname+"/lisap/CS511/TestImages/"+sequence_name+"_0.png");
		
			BufferedImage bi = null;

			bi = ImageIO.read(url);

			add(controls = new BlobDetectorControls(bi));
			controls.imagepanel.repaint();

			blobDetector.detectBlobs(bi); //this call will create background model and return null
			

	}catch(Exception e){
		System.out.println("Unable to open file " + e.getMessage());
		e.printStackTrace();
	}	
		
	}

    /** This method destroys this applet */
    public void destroy() {
        remove(controls);
    }

    /** This method starts this applet */
    public void start() {
    	controls.setEnabled(true);
    }

    
    /** This method stops this applet */
    public void stop() {
    	controls.setEnabled(false);
    }

    
    /** This method processes AWT events generated by this applet */
    public void processEvent(AWTEvent e) {
  
    }

    /** @return a String representation of this applet */
    public String getAppletInfo() {
        return "Person Detector Applet";
    }
	

	public static void main(String args[]){
		JFrame frame = new JFrame("Person Detector");
	    
	    frame.addWindowListener (new WindowAdapter()
	    {
	        public void windowClosing (WindowEvent event)
	    {
	        System.exit(0);
	    }
	    });
	    
	    PersonDetectorApplet applet = new PersonDetectorApplet();
	    if (args.length != 0)
	    	applet.sequence_name = args[0];
	    	
		applet.init();
		applet.start();
		
		frame.add("Center", applet);
	    frame.setSize(850, 450);
	    frame.setVisible(true);
	}

}

